/**
 * BoringTodo Web版应用
 * 实现任务管理功能，包括任务的添加、编辑、删除、完成等操作
 */
document.addEventListener('DOMContentLoaded', () => {
    // DOM元素
    const todoTable = document.getElementById('todoTable');
    const completedTable = document.getElementById('completedTable');
    const editTaskModal = document.getElementById('editTaskModal');
    const settingsModal = document.getElementById('settingsModal');
    const emailModal = document.getElementById('emailModal');
    const contextMenu = document.getElementById('contextMenu');
    
    // 当前选中的任务及其所属表格
    let selectedTaskId = null;
    let currentTable = null;
    
    // 屏幕截图定时器
    let screenshotTimer = null;
    
    // 初始化应用
    initApp();
    
    /**
     * 初始化应用
     */
    function initApp() {
        loadTasks();
        registerEventListeners();
        initScreenshotTimer();
    }
    
    /**
     * 加载任务数据并显示
     */
    function loadTasks() {
        renderTasks(todoTable, todoData.getNormalTasks());
        renderTasks(completedTable, todoData.getCompletedTasks());
    }
    
    /**
     * 渲染任务到表格
     * @param {HTMLElement} table 目标表格
     * @param {Array} tasks 任务数组
     */
    function renderTasks(table, tasks) {
        const tbody = table.querySelector('tbody');
        tbody.innerHTML = '';
        
        if (tasks.length === 0) {
            const emptyRow = document.createElement('tr');
            const emptyCell = document.createElement('td');
            emptyCell.textContent = '暂无任务';
            emptyCell.colSpan = 3;
            emptyCell.style.textAlign = 'center';
            emptyCell.style.padding = '20px';
            emptyRow.appendChild(emptyCell);
            tbody.appendChild(emptyRow);
            return;
        }
        
        tasks.forEach(task => {
            const row = document.createElement('tr');
            row.dataset.id = task.id;
            
            // 描述列
            const descCell = document.createElement('td');
            descCell.textContent = task.description;
            row.appendChild(descCell);
            
            // 日期列
            const dateCell = document.createElement('td');
            if (table === todoTable) {
                dateCell.textContent = task.expectedCompletionDate ? 
                    formatDate(task.expectedCompletionDate) : '';
            } else {
                dateCell.textContent = task.completionDate ? 
                    formatDate(task.completionDate) : '';
            }
            row.appendChild(dateCell);
            
            // 备注列
            const notesCell = document.createElement('td');
            notesCell.textContent = task.notes;
            row.appendChild(notesCell);
            
            // 单击事件
            row.addEventListener('click', (e) => {
                selectTask(row, table);
            });
            
            // 双击事件
            row.addEventListener('dblclick', (e) => {
                selectTask(row, table);
                editTask(task.id);
            });
            
            // 右键菜单事件
            row.addEventListener('contextmenu', (e) => {
                e.preventDefault();
                selectTask(row, table);
                showContextMenu(e);
            });
            
            tbody.appendChild(row);
        });
    }
    
    /**
     * 选中任务
     * @param {HTMLElement} row 选中的行
     * @param {HTMLElement} table 所属表格
     */
    function selectTask(row, table) {
        // 清除两个表格中的所有选中状态
        document.querySelectorAll('.task-table tbody tr').forEach(r => {
            r.classList.remove('selected');
        });
        
        // 设置选中状态
        row.classList.add('selected');
        selectedTaskId = row.dataset.id;
        currentTable = table;
    }
    
    /**
     * 注册事件监听器
     */
    function registerEventListeners() {
        // 关闭按钮事件
        document.querySelectorAll('.close').forEach(closeBtn => {
            closeBtn.addEventListener('click', (e) => {
                e.target.closest('.modal').style.display = 'none';
            });
        });
        
        // 点击模态框外部关闭
        window.addEventListener('click', (e) => {
            if (e.target.classList.contains('modal')) {
                e.target.style.display = 'none';
            }
        });
        
        // 点击其他区域关闭上下文菜单
        document.addEventListener('click', (e) => {
            contextMenu.style.display = 'none';
        });
        
        // 按钮事件
        document.getElementById('btnAddTask').addEventListener('click', showAddTaskModal);
        document.getElementById('btnDeleteTask').addEventListener('click', deleteSelectedTask);
        document.getElementById('btnMarkAsComplete').addEventListener('click', markTaskAsComplete);
        document.getElementById('btnEditTask').addEventListener('click', () => editTask(selectedTaskId));
        document.getElementById('btnMoveToTop').addEventListener('click', moveTaskToTop);
        document.getElementById('btnOpenChat').addEventListener('click', openChatWindow);
        document.getElementById('btnCopyWeeklyCompletedTasks').addEventListener('click', () => copyCompletedTasks(-7));
        document.getElementById('btnCopyMonthlyCompletedTasks').addEventListener('click', () => copyCompletedTasks(-30));
        document.getElementById('btnScreenshot').addEventListener('click', captureScreenshot);
        document.getElementById('btnSettings').addEventListener('click', showSettingsModal);
        document.getElementById('btnSendEmail').addEventListener('click', showEmailModal);
        
        // 新增：数据存储相关按钮
        document.getElementById('btnOpenDataFolder').addEventListener('click', showDataStorageInfo);
        document.getElementById('btnExportAllData').addEventListener('click', exportAllData);
        
        // 表单提交事件
        document.getElementById('editTaskForm').addEventListener('submit', handleTaskFormSubmit);
        document.getElementById('settingsForm').addEventListener('submit', handleSettingsFormSubmit);
        document.getElementById('emailForm').addEventListener('submit', handleEmailFormSubmit);
        
        // 表单取消按钮
        document.getElementById('btnCancelEdit').addEventListener('click', () => {
            editTaskModal.style.display = 'none';
        });
        document.getElementById('btnCancelSettings').addEventListener('click', () => {
            settingsModal.style.display = 'none';
        });
        document.getElementById('btnCancelEmail').addEventListener('click', () => {
            emailModal.style.display = 'none';
        });
        
        // 上下文菜单项
        document.getElementById('contextEdit').addEventListener('click', () => editTask(selectedTaskId));
        document.getElementById('contextDelete').addEventListener('click', deleteSelectedTask);
        document.getElementById('contextComplete').addEventListener('click', markTaskAsComplete);
        document.getElementById('contextTop').addEventListener('click', moveTaskToTop);
        document.getElementById('contextCopy').addEventListener('click', copyTaskDescription);
        
        // 键盘快捷键
        document.addEventListener('keydown', (e) => {
            // Ctrl+S: 保存数据
            if (e.ctrlKey && e.key === 's') {
                e.preventDefault();
                todoData.saveAllData();
                showNotification('数据已保存');
            }
        });
    }
    
    /**
     * 显示添加任务模态框
     */
    function showAddTaskModal() {
        const form = document.getElementById('editTaskForm');
        form.reset();
        
        // 设置预期完成时间为当天
        const dateInput = document.getElementById('taskDate');
        const today = new Date();
        dateInput.value = formatDateForInput(today);
        
        document.querySelector('#editTaskModal h2').textContent = '添加新任务';
        form.dataset.mode = 'add';
        editTaskModal.style.display = 'block';
        document.getElementById('taskDescription').focus();
    }
    
    /**
     * 编辑任务
     * @param {string} taskId 任务ID
     */
    function editTask(taskId) {
        if (!taskId) {
            showNotification('请先选择要编辑的任务', 'warning');
            return;
        }
        
        const task = todoData.getTaskById(taskId);
        if (!task) {
            showNotification('找不到任务数据', 'error');
            return;
        }
        
        const form = document.getElementById('editTaskForm');
        form.reset();
        
        // 填充表单数据
        document.getElementById('taskDescription').value = task.description;
        document.getElementById('taskNotes').value = task.notes;
        
        const dateInput = document.getElementById('taskDate');
        if (task.expectedCompletionDate) {
            dateInput.value = formatDateForInput(new Date(task.expectedCompletionDate));
        } else {
            dateInput.value = '';
        }
        
        // 设置表单模式和标题
        document.querySelector('#editTaskModal h2').textContent = '编辑任务';
        form.dataset.mode = 'edit';
        form.dataset.taskId = taskId;
        
        editTaskModal.style.display = 'block';
        document.getElementById('taskDescription').focus();
    }
    
    /**
     * 处理任务表单提交
     * @param {Event} e 提交事件
     */
    function handleTaskFormSubmit(e) {
        e.preventDefault();
        
        const description = document.getElementById('taskDescription').value.trim();
        const dateStr = document.getElementById('taskDate').value;
        const notes = document.getElementById('taskNotes').value.trim();
        
        if (!description) {
            showNotification('任务描述不能为空', 'warning');
            return;
        }
        
        const expectedCompletionDate = dateStr ? new Date(dateStr).toISOString() : null;
        
        const taskData = {
            description,
            notes,
            expectedCompletionDate
        };
        
        const form = e.target;
        if (form.dataset.mode === 'add') {
            // 添加新任务
            todoData.addTask(taskData);
            showNotification('任务已添加');
        } else {
            // 更新任务
            const taskId = form.dataset.taskId;
            todoData.updateTask(taskId, taskData);
            showNotification('任务已更新');
        }
        
        // 刷新任务列表
        loadTasks();
        
        // 关闭模态框
        editTaskModal.style.display = 'none';
    }
    
    /**
     * 删除选中的任务
     */
    function deleteSelectedTask() {
        if (!selectedTaskId) {
            showNotification('请先选择要删除的任务', 'warning');
            return;
        }
        
        if (confirm('确定要删除选中的任务吗？')) {
            if (todoData.deleteTask(selectedTaskId)) {
                showNotification('任务已删除');
                loadTasks();
                selectedTaskId = null;
            } else {
                showNotification('删除任务失败', 'error');
            }
        }
    }
    
    /**
     * 将任务标记为已完成
     */
    function markTaskAsComplete() {
        if (!selectedTaskId) {
            showNotification('请先选择要完成的任务', 'warning');
            return;
        }
        
        // 只有未完成的任务才能标记为完成
        if (currentTable !== todoTable) {
            showNotification('此任务已经完成', 'warning');
            return;
        }
        
        const updatedTask = todoData.markTaskAsComplete(selectedTaskId);
        if (updatedTask) {
            showNotification('任务已完成');
            loadTasks();
            selectedTaskId = null;
        } else {
            showNotification('更新任务状态失败', 'error');
        }
    }
    
    /**
     * 将任务置顶
     */
    function moveTaskToTop() {
        if (!selectedTaskId) {
            showNotification('请先选择要置顶的任务', 'warning');
            return;
        }
        
        if (todoData.moveTaskToTop(selectedTaskId)) {
            showNotification('任务已置顶');
            loadTasks();
        } else {
            showNotification('置顶任务失败', 'error');
        }
    }
    
    /**
     * 复制任务描述到剪贴板
     */
    function copyTaskDescription() {
        if (!selectedTaskId) {
            showNotification('请先选择任务', 'warning');
            return;
        }
        
        const task = todoData.getTaskById(selectedTaskId);
        if (task) {
            navigator.clipboard.writeText(task.description)
                .then(() => {
                    showNotification('任务描述已复制到剪贴板');
                })
                .catch(err => {
                    showNotification('复制失败: ' + err, 'error');
                });
        }
    }
    
    /**
     * 复制特定时间范围内的已完成任务到剪贴板
     * @param {number} days 天数范围，负数表示过去的天数
     */
    function copyCompletedTasks(days) {
        const tasks = todoData.getCompletedTasksInRange(days);
        
        if (tasks.length === 0) {
            showNotification('指定时间范围内没有已完成的任务', 'warning');
            return;
        }
        
        const prompt = todoData.settings.reportPrompt || '请根据以下完成的任务，总结一下我的工作内容，用第一人称：';
        let content = prompt + '\n------------\n';
        
        tasks.forEach(task => {
            content += `描述: ${task.description}\n`;
            content += `完成时间: ${formatDate(task.completionDate)}\n`;
            content += `备注: ${task.notes}\n`;
            content += '------------\n';
        });
        
        navigator.clipboard.writeText(content)
            .then(() => {
                showNotification(`已复制${tasks.length}个任务到剪贴板`);
            })
            .catch(err => {
                showNotification('复制失败: ' + err, 'error');
            });
    }
    
    /**
     * 显示设置模态框
     */
    function showSettingsModal() {
        const settings = todoData.settings;
        
        document.getElementById('enableAutoScreenshot').checked = settings.enableAutoScreenshot;
        document.getElementById('screenshotInterval').value = settings.screenshotIntervalMinutes;
        document.getElementById('reportPrompt').value = settings.reportPrompt;
        
        settingsModal.style.display = 'block';
    }
    
    /**
     * 处理设置表单提交
     * @param {Event} e 提交事件
     */
    function handleSettingsFormSubmit(e) {
        e.preventDefault();
        
        const newSettings = {
            enableAutoScreenshot: document.getElementById('enableAutoScreenshot').checked,
            screenshotIntervalMinutes: parseInt(document.getElementById('screenshotInterval').value, 10),
            reportPrompt: document.getElementById('reportPrompt').value
        };
        
        todoData.saveSettings(newSettings);
        
        // 更新截图定时器
        initScreenshotTimer();
        
        showNotification('设置已保存');
        settingsModal.style.display = 'none';
    }
    
    /**
     * 显示邮件设置模态框
     */
    function showEmailModal() {
        emailModal.style.display = 'block';
    }
    
    /**
     * 处理邮件表单提交
     * @param {Event} e 提交事件
     */
    function handleEmailFormSubmit(e) {
        e.preventDefault();
        
        // 在真实环境中，这里会调用邮件发送API
        // 在Web版中，我们只模拟这个功能
        showNotification('Web版不支持直接发送邮件，请下载数据并通过您的邮箱客户端发送', 'info');
        
        const jsonData = todoData.exportData();
        downloadFile('boringtodo_backup.json', jsonData);
        
        emailModal.style.display = 'none';
    }
    
    /**
     * 下载文件
     * @param {string} filename 文件名
     * @param {string} content 文件内容
     */
    function downloadFile(filename, content) {
        const blob = new Blob([content], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    }
    
    /**
     * 初始化截图定时器
     */
    function initScreenshotTimer() {
        // 清除现有定时器
        if (screenshotTimer) {
            clearInterval(screenshotTimer);
            screenshotTimer = null;
        }
        
        // 如果启用了自动截图，设置新定时器
        if (todoData.settings.enableAutoScreenshot) {
            const interval = todoData.settings.screenshotIntervalMinutes * 60 * 1000;
            screenshotTimer = setInterval(captureScreenshot, interval);
        }
    }
    
    /**
     * 捕获屏幕截图
     * 在Web版中，这个功能有限制，所以我们只是模拟它
     */
    function captureScreenshot() {
        // 在Web版中，由于安全限制，我们无法进行真正的屏幕截图
        showNotification('截图功能在Web版中受限。在桌面应用中才能完全支持此功能。', 'info');
    }
    
    /**
     * 显示聊天窗口
     * 在Web版中，我们只是打开一个新窗口
     */
    function openChatWindow() {
        window.open('https://chat.deepseek.com/', '_blank');
    }
    
    /**
     * 显示上下文菜单
     * @param {Event} e 鼠标事件
     */
    function showContextMenu(e) {
        // 设置菜单位置
        contextMenu.style.left = `${e.pageX}px`;
        contextMenu.style.top = `${e.pageY}px`;
        
        // 根据当前表格调整菜单项
        const completeItem = document.getElementById('contextComplete');
        if (currentTable === todoTable) {
            completeItem.style.display = 'block';
        } else {
            completeItem.style.display = 'none';
        }
        
        // 显示菜单
        contextMenu.style.display = 'block';
    }
    
    /**
     * 格式化日期显示
     * @param {string} dateStr ISO格式的日期字符串
     * @returns {string} 格式化后的日期字符串
     */
    function formatDate(dateStr) {
        if (!dateStr) return '';
        
        const date = new Date(dateStr);
        return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())} ${padZero(date.getHours())}:${padZero(date.getMinutes())}`;
    }
    
    /**
     * 为日期输入框格式化日期
     * @param {Date} date 日期对象
     * @returns {string} 格式化后的日期字符串
     */
    function formatDateForInput(date) {
        if (!date) return '';
        
        return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())}T${padZero(date.getHours())}:${padZero(date.getMinutes())}`;
    }
    
    /**
     * 数字补零
     * @param {number} num 数字
     * @returns {string} 补零后的字符串
     */
    function padZero(num) {
        return num < 10 ? `0${num}` : num;
    }
    
    /**
     * 显示通知消息
     * @param {string} message 消息内容
     * @param {string} type 消息类型: info, success, warning, error
     */
    function showNotification(message, type = 'success') {
        // 创建通知元素
        const notification = document.createElement('div');
        notification.className = 'notification';
        notification.classList.add(type);
        
        // 设置图标
        let icon = '';
        switch (type) {
            case 'success': icon = 'bi-check-circle-fill'; break;
            case 'warning': icon = 'bi-exclamation-triangle-fill'; break;
            case 'error': icon = 'bi-x-circle-fill'; break;
            default: icon = 'bi-info-circle-fill';
        }
        
        notification.innerHTML = `
            <i class="bi ${icon}"></i>
            <span>${message}</span>
        `;
        
        // 添加到页面
        document.body.appendChild(notification);
        
        // 设置通知样式
        notification.style.cssText = `
            position: fixed;
            bottom: 20px;
            right: 20px;
            padding: 12px 20px;
            background-color: white;
            border-left: 4px solid #3498db;
            border-radius: 4px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
            z-index: 9999;
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 14px;
            color: #333;
            min-width: 250px;
            max-width: 350px;
            opacity: 0;
            transform: translateY(20px);
            transition: all 0.3s ease;
        `;
        
        // 根据类型设置颜色
        switch (type) {
            case 'success': notification.style.borderLeftColor = '#27ae60'; break;
            case 'warning': notification.style.borderLeftColor = '#f39c12'; break;
            case 'error': notification.style.borderLeftColor = '#e74c3c'; break;
            default: notification.style.borderLeftColor = '#3498db';
        }
        
        // 添加图标样式
        notification.querySelector('i').style.cssText = `
            font-size: 18px;
            color: ${notification.style.borderLeftColor};
        `;
        
        // 显示通知
        setTimeout(() => {
            notification.style.opacity = '1';
            notification.style.transform = 'translateY(0)';
        }, 10);
        
        // 3秒后隐藏并移除通知
        setTimeout(() => {
            notification.style.opacity = '0';
            notification.style.transform = 'translateY(20px)';
            
            setTimeout(() => {
                document.body.removeChild(notification);
            }, 300);
        }, 3000);
    }
    
    // 添加通知样式
    const notificationStyle = document.createElement('style');
    notificationStyle.textContent = `
        @keyframes notification-slide-in {
            0% { opacity: 0; transform: translateY(20px); }
            100% { opacity: 1; transform: translateY(0); }
        }
        @keyframes notification-slide-out {
            0% { opacity: 1; transform: translateY(0); }
            100% { opacity: 0; transform: translateY(20px); }
        }
    `;
    document.head.appendChild(notificationStyle);
    
    /**
     * 显示数据存储信息
     */
    function showDataStorageInfo() {
        // 因为Web应用无法直接访问文件系统，所以我们显示一个弹窗来展示存储信息
        const normalTasksCount = todoData.getNormalTasks().length;
        const completedTasksCount = todoData.getCompletedTasks().length;
        
        // 计算LocalStorage使用情况
        let totalSize = 0;
        for (let key in localStorage) {
            if (localStorage.hasOwnProperty(key)) {
                totalSize += (localStorage[key].length + key.length) * 2; // 每个字符约2字节
            }
        }
        
        // 转换为合适的单位
        let sizeDisplay = totalSize + ' 字节';
        if (totalSize > 1024) {
            sizeDisplay = (totalSize / 1024).toFixed(2) + ' KB';
        }
        if (totalSize > 1024 * 1024) {
            sizeDisplay = (totalSize / (1024 * 1024)).toFixed(2) + ' MB';
        }
        
        // 创建并显示信息模态框
        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.style.display = 'block';
        
        modal.innerHTML = `
            <div class="modal-content" style="width: 400px;">
                <span class="close">&times;</span>
                <h2>数据存储信息</h2>
                <div class="info-list">
                    <div class="info-item">
                        <span class="info-label">存储位置:</span>
                        <span class="info-value">浏览器 LocalStorage</span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">待办任务数:</span>
                        <span class="info-value">${normalTasksCount}</span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">已完成任务数:</span>
                        <span class="info-value">${completedTasksCount}</span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">存储占用:</span>
                        <span class="info-value">${sizeDisplay}</span>
                    </div>
                </div>
                <div class="storage-note">
                    <i class="bi bi-exclamation-circle"></i>
                    <p>Web应用数据存储在浏览器中，清除浏览器数据可能会导致任务数据丢失。建议定期导出备份。</p>
                </div>
                <div class="form-actions">
                    <button type="button" class="btn btn-primary" id="btnDataInfoExport">导出数据备份</button>
                    <button type="button" class="btn btn-secondary" id="btnDataInfoClose">关闭</button>
                </div>
            </div>
        `;
        
        document.body.appendChild(modal);
        
        // 添加模态框样式
        const styleElem = document.createElement('style');
        styleElem.textContent = `
            .info-list {
                margin: 15px 0;
            }
            .info-item {
                display: flex;
                padding: 8px 0;
                border-bottom: 1px solid #eee;
            }
            .info-label {
                font-weight: bold;
                width: 120px;
            }
            .info-value {
                flex: 1;
            }
            .storage-note {
                background-color: #f8f9fa;
                border-left: 4px solid #f39c12;
                padding: 10px;
                margin: 15px 0;
                display: flex;
                gap: 10px;
                align-items: flex-start;
            }
            .storage-note i {
                color: #f39c12;
                font-size: 18px;
            }
            .storage-note p {
                margin: 0;
                font-size: 13px;
                line-height: 1.4;
                color: #555;
            }
        `;
        document.head.appendChild(styleElem);
        
        // 关闭按钮事件
        modal.querySelector('.close').addEventListener('click', () => {
            document.body.removeChild(modal);
        });
        
        // 关闭按钮事件
        modal.querySelector('#btnDataInfoClose').addEventListener('click', () => {
            document.body.removeChild(modal);
        });
        
        // 导出按钮事件
        modal.querySelector('#btnDataInfoExport').addEventListener('click', () => {
            exportAllData();
        });
        
        // 点击模态框外部关闭
        modal.addEventListener('click', (e) => {
            if (e.target === modal) {
                document.body.removeChild(modal);
            }
        });
    }
    
    /**
     * 导出所有数据
     */
    function exportAllData() {
        const jsonData = todoData.exportData();
        const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
        downloadFile(`boringtodo_backup_${timestamp}.json`, jsonData);
        showNotification('所有数据已成功导出');
    }
}); 